package com.vision.common.aes;

import com.vision.common.exception.CodeException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

public class AES {

    private static final String algorithmStr = "AES/ECB/PKCS5Padding";

    private static final String TAG = "AES";

    static private KeyGenerator keyGen;

    static private Cipher cipher;

    static boolean isInited = false;

    // private static void init() {
    //     try {
    //         /**为指定算法生成一个 KeyGenerator 对象。
    //          *此类提供（对称）密钥生成器的功能。
    //          *密钥生成器是使用此类的某个 getInstance 类方法构造的。
    //          *KeyGenerator 对象可重复使用，也就是说，在生成密钥后，
    //          *可以重复使用同一 KeyGenerator 对象来生成进一步的密钥。
    //          *生成密钥的方式有两种：与算法无关的方式，以及特定于算法的方式。
    //          *两者之间的惟一不同是对象的初始化：
    //          *与算法无关的初始化
    //          *所有密钥生成器都具有密钥长度 和随机源 的概念。
    //          *此 KeyGenerator 类中有一个 init 方法，它可采用这两个通用概念的参数。
    //          *还有一个只带 keysize 参数的 init 方法，
    //          *它使用具有最高优先级的提供程序的 SecureRandom 实现作为随机源
    //          *（如果安装的提供程序都不提供 SecureRandom 实现，则使用系统提供的随机源）。
    //          *此 KeyGenerator 类还提供一个只带随机源参数的 inti 方法。
    //          *因为调用上述与算法无关的 init 方法时未指定其他参数，
    //          *所以由提供程序决定如何处理将与每个密钥相关的特定于算法的参数（如果有）。
    //          *特定于算法的初始化
    //          *在已经存在特定于算法的参数集的情况下，
    //          *有两个具有 AlgorithmParameterSpec 参数的 init 方法。
    //          *其中一个方法还有一个 SecureRandom 参数，
    //          *而另一个方法将已安装的高优先级提供程序的 SecureRandom 实现用作随机源
    //          *（或者作为系统提供的随机源，如果安装的提供程序都不提供 SecureRandom 实现）。
    //          *如果客户端没有显式地初始化 KeyGenerator（通过调用 init 方法），
    //          *每个提供程序必须提供（和记录）默认初始化。
    //          */
    //         keyGen = KeyGenerator.getInstance(TAG);
    //     } catch (NoSuchAlgorithmException e) {
    //         e.printStackTrace();
    //     }
    //     // 初始化此密钥生成器，使其具有确定的密钥长度。
    //     keyGen.init(128); //128位的AES加密
    //     try {
    //         // 生成一个实现指定转换的 Cipher 对象。
    //         cipher = Cipher.getInstance(algorithmStr);
    //     } catch (NoSuchAlgorithmException e) {
    //         e.printStackTrace();
    //     } catch (NoSuchPaddingException e) {
    //         e.printStackTrace();
    //     }
    //     //标识已经初始化过了的字段
    //     isInited = true;
    // }

    // private static byte[] genKey() {
    //     if (!isInited) {
    //         init();
    //     }
    //     //首先 生成一个密钥(SecretKey),
    //     //然后,通过这个秘钥,返回基本编码格式的密钥，如果此密钥不支持编码，则返回 null。
    //     return keyGen.generateKey().getEncoded();
    // }

    // private static byte[] encrypt(byte[] content, byte[] keyBytes) {
    //     byte[] encryptedText = null;
    //     if (!isInited) {
    //         init();
    //     }
    //     /**
    //      *类 SecretKeySpec
    //      *可以使用此类来根据一个字节数组构造一个 SecretKey，
    //      *而无须通过一个（基于 provider 的）SecretKeyFactory。
    //      *此类仅对能表示为一个字节数组并且没有任何与之相关联的钥参数的原始密钥有用
    //      *构造方法根据给定的字节数组构造一个密钥。
    //      *此构造方法不检查给定的字节数组是否指定了一个算法的密钥。
    //      */
    //     Key key = new SecretKeySpec(keyBytes, TAG);
    //     try {
    //         // 用密钥初始化此 cipher。
    //         cipher.init(Cipher.ENCRYPT_MODE, key);
    //     } catch (InvalidKeyException e) {
    //         e.printStackTrace();
    //     }
    //     try {
    //         //按单部分操作加密或解密数据，或者结束一个多部分操作。(不知道神马意思)
    //         encryptedText = cipher.doFinal(content);
    //     } catch (IllegalBlockSizeException e) {
    //         e.printStackTrace();
    //     } catch (BadPaddingException e) {
    //         e.printStackTrace();
    //     }
    //     return encryptedText;
    // }

    private static byte[] encrypt(String content, String password) throws Exception {
        byte[] keyStr = getKey(password);
        SecretKeySpec key = new SecretKeySpec(keyStr, TAG);
        Cipher cipher = Cipher.getInstance(algorithmStr);//algorithmStr
        byte[] byteContent = content.getBytes("utf-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);//   ʼ
        return cipher.doFinal(byteContent);
    }

    private static byte[] decrypt(byte[] content, String password) throws Exception {
        byte[] keyStr = getKey(password);
        SecretKeySpec key = new SecretKeySpec(keyStr, TAG);
        Cipher cipher = Cipher.getInstance(algorithmStr);//algorithmStr
        cipher.init(Cipher.DECRYPT_MODE, key);//   ʼ
        return cipher.doFinal(content);
    }

    private static byte[] getKey(String password) {
        byte[] rByte = null;
        if (password != null) {
            rByte = password.getBytes();
        } else {
            rByte = new byte[24];
        }
        return rByte;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuilder sb = new StringBuilder();
        for (byte aBuf : buf) {
            String hex = Integer.toHexString(aBuf & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    //注意: 这里的password(秘钥必须是16位的)
    private static final String keyBytes = "avsdeffabddefg12";

    /**
     * 加密
     */
    public static String encode(String content) throws CodeException {
        try {
            //加密之后的字节数组,转成16进制的字符串形式输出
            return parseByte2HexStr(encrypt(content, keyBytes));
        } catch (Exception e) {
            throw new CodeException("eCodeException:{}" + content, e);
        }
    }

    /**
     * 解密
     */
    public static String decode(String content) throws CodeException {
        //解密之前,先将输入的字符串按照16进制转成二进制的字节数组,作为待解密的内容输入
        try {
            byte[] b = decrypt(parseHexStr2Byte(content), keyBytes);
            return new String(b);
        } catch (Exception e) {
            throw new CodeException("dCodeException:{}" + content, e);
        }
    }

    //测试用例
    public static void test1() {
        try {
            String content = "{\"activateCode\":\"111\",\"date\":1496070210404,\"imei\":\"ejh98w2398\",\"unique\":\"slkd\"}";
            // String pStr = "6DC668FAE20347507C4A921F00A22F84F9CB8AFEA62854203974AA057D3B4ADE4FD164EA85046B8412D248083F89517CAB9D80195B2B6187264254D23CB3B7E6D8E5A9793AB135A6DE3175D73CB2A993D07019FA6473517A3579E9B32D25401F90028513213919FF387BCFC11864B380173A8879AF54B92E3A223AD5BEF41A736DAE86B22176ADE8F0FD446187B80B7DABC7F24436A2A370DF18880341515820AB3E082AC99AD31FB9EA6E8563402A9ACFC1F30DCD18EC699B66F05DB7629D9C494C6E61D286E45ACA67B85C7B0DDAD291E0B9CEEE0EDB9C6368ED352040406B5AB542BB0EF3E9C0424C4E550402EA7E85DD63BED24F05DB5C89F0A8D8C64D7AB94F7C8082EC65183D704F1F892E1A35E2570886387E0DF2A8E680997DB0198BE449B299E7DAE635CE3A8DB5FB06FD9034C7EEDD1AD8C6D019BDD8EFD72BC871241911C2B5DDDA51D27C8709856332364295CD04B86D4BE264BF48EF431429475E4CEF91CED0DA095194F9B23E08E80F79187AC712D2C774FCEAB66146D59CD1F83E06842A6D46B1780C53CA79DA7908BAFC70390F18D17163B3C137999B8CEFEC549112EA3C9C90600911C375577A1994BAA6327B96B60B82BE3F64857890C5584E08102B0268E5E24FB62661C7BE2360464A5FD411075861FDD6C72FC078234BE96705C55DDED0651D3C8B8F6FA0B350CA153B41B66FCF436B505173045DEAE0D9465BD0ABF60DB5D2D371C93695566DAD0A968D84AA86A90B4E6CD472AF7A7E1C71308567D1ABF04F67A088989100E61BF22782A705593EA1770816DE3C3CDAAC94AD1C842366493BC9612F0D2AD6951941760AE02CE77F3A7C4902D1625BA3D8D335FFA1FEFA20E5C4EA7F10D1C3AB761E199531ABB7048C6C4E70C4B457A72F4003A3E82B0826557BBBBA0985B56D71B25321DCF7D1E4D2B8BE92E60E7990028513213919FF387BCFC11864B38078F1F2AEC76074835CAD85979B9C1BFEDD824275091508F43D0043B9F8B089D8029E24596C7D019CFC9A035F727BE2799F2132224E4B918F72A68B35D64D25E9DF0B6129AD3BC4CE4A162ACE53A423A54A9B77B82859435B07235475AD41570C3FB02714289F006215FA9127BE21F2060C71174C4D80234F8D2079AE113D3F782A92780AE60474E71F2882F912E10137E0A26E653D7C74171B5601AE402AF6FCB9A9DCDC1F21DCE901D625414C631661149DFBDFC5765CC2CBE3FDA7DF386A1F1DAD4CB414DC7A148E676667E7DE7AFEE92F4CD93F5F7A5475CB44892CFC3B8390028513213919FF387BCFC11864B38027EF65740CCE8248595C17529D96376A2EB5080CCB42A1EBA62EB0736B34887619988F30D7B9F3F15D4E9A6C73C54D319C70ED45EC99E8144B443B3D27701103E84DD9F5369D7FC9D10D469430AAB9B6268F791A4337FA50C85FC278B6AED6BCABE4D2953E47DD4A7B93892478EDB2224C87D621135C31AF868CAB911A79161C683008CC956099989C8E577157F432767477BF53EE0691000F975D1E2508FF664487EA57D9DBF993FDFB58B4D7B1FB604E785BBF639B0AFF33F56CBBBD94BEEF5AC63CC7EC8BE6B9AE89C936F67FEAA10E92CA590752BF9CDCD4AB7D2B2D23B23477EC92E8A16F00892564B2CABF1DB54AE43414825AB0C192299E9FE129BBBF37AE9FA399C0034453C4B005B42F796CD9420674F6B7A7B13B4B0CEDE9D7F52421B740E078A4E7936DEA37498D63CECEF5BB49847F9C12C0AA5D374795C62F52F5A167F9851497C59A1905C5B7EB13F6962D6D6BEDABF21D6B7B8386466053E599711245BF01695ECBF8843C23C2C8AC07228B83190B70CEE04D525F7BD6D990F002A8FEBA321CFB8E5A185D0751458CCBE78A549965F11B91FB8C52678FE43AA0B3A2282004EAC4661AF0CD013641BA494C6E61D286E45ACA67B85C7B0DDAD2DF178638D7C571BD71CB1A40C88C1719D423267A51219DE2D582B0E45F3E1C57DE84E6C07D9CA1052F93338CEBF05A34D95D05E38A42BD1E321A09B262CD2FB15116EB8C2E008347F248B1B3C443D8B0D3BC8AF9AF2559565838DA6D8B281E93BC4DCD671FD5340023485D1A6FC363C783B3C380D82735D7C5B6AD6562A3B7A18AB0F5839A2085C873A4DB17BE5DEE5462C4143128806C4F855338C71810F4A384E8A2B58A9689401FE87A8FFE287DE5829F7764F3C3525696B7FF301386AD95C99B26E1DECF45BE027C1D8D30B23A73DD4C252E51D01DA12519E87FE3AF4389B70E00F382CBCA5116EFA7B8B67EFA4BED97ED3A50C9CB6C1B63236E3A5AEBD0CC09ED0FFA951C6863730994C94EC9A9010E585A2A2D6B25D0031EDA6415C70928380D38BF3DC6BA4E4B15223E1710366619EF5346D4A3397999C443D6AEE06FFDB96C61FA19D1AAE66EF7D3EEC01AECC717B45AA879C7202FB1E20E99AB11D4930F74B6B3FAFD055DAE93E279A1EAD9A7F2A791963F4C6131897509B58B3B951DAD4CB414DC7A148E676667E7DE7AFEE92F4CD93F5F7A5475CB44892CFC3B8390028513213919FF387BCFC11864B38027EF65740CCE8248595C17529D96376AF32E8CD8A3BA3903FCFAD1BF92FD54DDD4495C2E056526765EB42B74139B33D4A2744A7B9EE639DE5869B73F77E4DDA683EE440E10BDC71D9A4C9C277C8AB7100EA639EAAC102647CA26F61D8DE1C9A6ABE4D2953E47DD4A7B93892478EDB2224C87D621135C31AF868CAB911A79161C683008CC956099989C8E577157F432767477BF53EE0691000F975D1E2508FF66D72DBEA147EC28A4E1F608835FF841FC0ECCAF76D61A88F4C26EBD7858B4A04F51D7DC9E0C84620168FB8FFA400C8B0F8AB0F5839A2085C873A4DB17BE5DEE549ED91F9EBA885E7BBEF910C18FFE2F6CBE49F2708BB518D5FED5ACB3E8FEB92876CD74116BA7037C32E811E40D0F9FAB3DFDD0B21CDBCF110F1ECA12EE51C5486B6FE34EC020E9CE43D966BA5EFF34E721250327A409A5E843C2920AED810CDEB3F439CE25EE02D672E430355F1014B30367364A0BDAD05D051C32460CBC83637D0BE1F871EF0C2119A417778EB4B1552CF3CE3272E8D356B3F22B8D37DCB51AB4C4AC5395CC2E2790D37EF28169DD6DAD6FC42B1C7C847B5010D41A62522E45683008CC956099989C8E577157F432760D294D750FF5AFCCC3396C4528A70E2E38F6A27E9D2E80CA22598AABE263553050B4664E3BFEF968E2CD8186851C1CA6135833C3411D7AF6C918B52B31D93AB5401D36ABC1719DA3A50CC552F744FF5E77938A72E19EEC674AFE9A01BF622F3680CFDC899C1D0885D22F0FAB0D18D9D6CE8475816E48F7BF42D240BA0B934AE8D0C71A77A577A32C1F204A454FD055BDB82E87BF14D6E2CA4F8598D4EFA3315216568B3120F264FD8BF550282FFCDB46C5E2C1C3A769483D97080E1323B57FE4F8486B86E20E16CBD8D4FCEBDA860F5878B50CB7715890AE4587DDEE9E4229D95AC63CC7EC8BE6B9AE89C936F67FEAA10E92CA590752BF9CDCD4AB7D2B2D23B23477EC92E8A16F00892564B2CABF1DB54AE43414825AB0C192299E9FE129BBBF9308D7A3A62DEC15C3368590674C43953BA6597424F490F7B234204079A45C2DAE7628A148D1020CDE8F608248907D10056B2D136102181F23C76D216CE1EA35201F20D84EF5EAE7253377BDBB29C92C746908C2DD250E2BDC4D595590EA1AFB2C37C659315F05CDCDF1BF013E0CA6D8142EC8796BECEA696F7A6683A1F45192BBF0751FA99F5AC7FD04A67141D9AA84673F76754BEDD04207E2E925F4984B688F099D6E686FF4A38E254979067BD952F64C7A05AD841731297043247961B66E1DB26EF9A6940EF689061E61E3A459E138DC83DE08C8CBDCA855B3B55F7F23D8E55DDE99CB97E6BC8310666787BF9250DE546379015FE8495DD7006AF1364984D8E5A9793AB135A6DE3175D73CB2A993D07019FA6473517A3579E9B32D25401F90028513213919FF387BCFC11864B380173A8879AF54B92E3A223AD5BEF41A737C6AB1B5D6C17C4B24C45C3D0281A2FC1920B452E1C75BBFBDCC59BF2A6C41050D80C111CEB8F33DC4526C6D0F2497A1494C6E61D286E45ACA67B85C7B0DDAD291E0B9CEEE0EDB9C6368ED352040406B5AB542BB0EF3E9C0424C4E550402EA7E2FEB13FA45474581E698571AD6A37830B94F7C8082EC65183D704F1F892E1A354F3A5235AF01C1D3EE5341E614F2A6A075A374593313BF4288A454A41988E88FFDB96C61FA19D1AAE66EF7D3EEC01AECC717B45AA879C7202FB1E20E99AB11D4930F74B6B3FAFD055DAE93E279A1EAD9B3749362126984F4A70EA294D893F0601DAD4CB414DC7A148E676667E7DE7AFEE92F4CD93F5F7A5475CB44892CFC3B8390028513213919FF387BCFC11864B38027EF65740CCE8248595C17529D96376A1CA8CC527B00B9D95915127593590AB82666D4DE4BD498E448E66C9EE2AD4B590AB958A9CFB33D376C686CBBF470D4A85460EDD88410BCD841ECCC7D358DCBEEAD16C1317F91F075A854705662E1C459ABE4D2953E47DD4A7B93892478EDB2224C87D621135C31AF868CAB911A79161C683008CC956099989C8E577157F432767477BF53EE0691000F975D1E2508FF668468388C4E2F2DF1469972D540315F81B1DED730BA2F72C768505B8C5A8B5262DA9382667D48A396310A8C6611010C482120C26ED069319B5343A0F15B5899DA8AB0F5839A2085C873A4DB17BE5DEE549ED91F9EBA885E7BBEF910C18FFE2F6CBE49F2708BB518D5FED5ACB3E8FEB928AE56731E5DC756722249C8317F2DFF5C3DFDD0B21CDBCF110F1ECA12EE51C548864042DB3DB9BD49A9E212F640A968A6C204A26D12713676E3FEEC8BCC8BFE127EBF8353D726DF16F258BCC87558F80E4EB57C43802290BA3AF8DB97B9BAE7A450C2C34BCB623454EDF45245F391C0FCAAEDC5FBBDD1EBD61C351FFBA0065A738FFA032F6A0139DD922E7ECE01F7513E236D4A3677A157747DEDC5CC34766864BCD198475D32FBE0E28F4379014670AFD892F83F5FF0D52EFF89F4B9E642B3D35AC63CC7EC8BE6B9AE89C936F67FEAA171F0BE0D745815981E74ED31086CADDAF401AC48D8D26F0F06552BF5B98C623E3A52D5D7BCC00C8CC8ABB0C4FE0F603A768697D1E84ED44D269E23722BAAB3A602B1E66374BF8C10B2935424727A30962708D1AAE4342FF4178373D5B28EA863B38A7995173C56CECBBE7285B8806D863707DB537FC3AE74E7079A9DE9230CC077345CB1FA19069CC5C6C5BBA5F99AAE49D577150ADAB2A5AFB2BFDDE0BABF2F3AED163916BFD5A6131E82C81523FD8C9671617E9DD4B68C4F10B5B164FDED865590779C290457DF4C244FE7AD0E44FEC823983DE1FFED5831B7E04B73CAA89EF56F3CB2DF66A48269D68094E79F5F5EE4D0883A811B0CE4F2D3B068F47B4518AC08C5F6D9F6E1A6554804577912BAAA7E56C474C2912E15734A993537F84DFC47C7FB4C15558717A010C584BC2FC29B009EB392D3351D59AA868A87727256B558EDE0672FD614C22ABF182A9830A78038D9FBCCB54601E1A6C7AB6E8999D26307DB7571C1A445085FED4BE4EBA1025475E924F9860BE952B5116269B78AFC4240B9ECEC4918132AE40B943A6D7550219F2E55E54CA1678988F6D8FED7A993645386A27664ABFCA4EB0F7C430BF0DF4F088077BB47B053639C67497F7D5630E5C24D543ADE4D714E04691B18E1EACA2E4046D1FEA34AA967F94EDB6FD9BA2536E410DC6B2DED9BB74B598E496E243BC9025CCB50D77C0C6EE04712607517B892BF7EEDF848F6DBDA30052A47A03BC5A205B1C4B185087341921175621617000544F9B88798F69B5EAEB46AA648068F7BD3F8830E12F059CE9819F004BEAEBE77494C6E61D286E45ACA67B85C7B0DDAD28A75AC00801123D31DC62AC8D93F431A4F959001D97F763094154ECE6DBF45A7D960F5BABDD49C469CF18D615435D4ED9E2A794079FBA3F1158C7959AACD4C174DC3D4926CBD3C5EEC875FA2A321ADB91028DD33B631B062146691CDC99D2E9FBEE970EB1E2AB0F9238F15DE85ED3404330B8B6ED735823155F434201F7F35FD4CF3A86CC4FD3464AE1BAD015DE92E342EF0CA1CD4734F5673A647A4C1577C7C474A7A375373E1851D77E109EEA9D8390352539EEC80DE1CC50205BC4DC8A419AAF4977D73E9AB41BC834D9BAF92D7CDA1FBBDD5A248A3A1905FE7A5DB97807B6FA6233D397D72B27F6F37D40527765F1B73381821D1CE080EF6FA695BC6464D87CF66BE24BB2C5461BE0FAD5B091F91B46FEAF6F3A223533AC54D33732A7E862C497D5A8426A1B8C268233F2EB6995137974C2C1604E2CEA7CCF6CA5DAAD07AD1035BADF730CA17C32F65F3C7D61E907888DB13FAB06576583722DA354BCFD699C76B4F61E8D66B7D51F31FA58843EA1C1E5A24C51A85E4B98561AD02F4B6708424C8D3714F229D41C4752F107DF0386A872335B1CE0D6C38CFF8A505562AD58D8EC12ED8F886290DF233A294F2BEC5FC96A5AB72BF3AE6AECB920945BA653D81684F073FD943BFDD8CBCDACDD67B28741764A4ACF8AE21FFD9972372470216CBF81FA5AE7127255649A36BC62ED9F709B37372DFF3B9FD213FFA8505D21F62";
            String pStr = encode(content);
            System.out.println("加密前：" + content);
            System.out.println("加密后:" + pStr);
            String postStr = null;
            postStr = decode(pStr);
            System.out.println("解密后：" + postStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        test1();
        // Video91QueryOrder video91QueryOrder = new Video91QueryOrder();
        // video91QueryOrder.setWord("jdjd");
        // video91QueryOrder.setCurrPage(10);
        // String s = JSON.toJSONString(video91QueryOrder);
        // System.out.println(s);
    }
}